<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015-5-20
 * Time: 10:02
 * this file is for single image upload function
 */

namespace doumiaoduo\ueditor;


use yii\widgets\InputWidget;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;

class VideoUploadMultiple extends InputWidget
{


    public $clientOptions = [];

    public $serverParam = [];

    public $buttonOptions = [];

    public $view;
    public $asset;

    public function init()
    {
        parent::init();
        $id = str_replace('-', '_', $this->options['id']);
        if (isset($this->clientOptions['serverUrl'])) {
            $this->clientOptions['serverUrl'] = str_replace('action', 'uploadvideo', $this->clientOptions['serverUrl']);
            $this->clientOptions['serverUrl'] = str_replace(urlencode('action'), 'uploadvideo', $this->clientOptions['serverUrl']);
        }
        $this->clientOptions['csrf-param'] = \Yii::$app->request->csrfParam;
        $this->clientOptions['csrf-token'] = \Yii::$app->request->getCsrfToken();
        $this->buttonOptions['id'] = isset($this->buttonOptions['id']) ? $this->buttonOptions['id'] : "video_upload_button_{$this->options['id']}";
        $this->view = $this->getView();
        $this->asset = VideoUploadMultipleAsset::register($this->view);
    }

    public function run()
    {
        $strHtml = '';
        $id=str_replace('-','_',$this->options['id']);
        $num = 0;

        if(!empty(Html::getAttributeValue($this->model, 'videoList'))){

            $videoListValues=explode('#|#',Html::getAttributeValue($this->model, 'videoList'));
            $num=count($videoListValues);
            $strHtml .= "<div><ul class='videolist'>";
            for($i=0;$i<$num;$i++) {
                /*$is_default = 0;
                if(Html::getAttributeValue($this->model,'video')==$videoListValues[$i]){
                    $is_default = 1;
                }*/
                $strHtml .= "<li style='float:left;margin-left:5px;'><div style='position:relative;'><video width=\"320\" height=\"240\" controls>
                    <source src=\"{$videoListValues[$i]}\" type=\"video/mp4\">
                    <source src=\"{$videoListValues[$i]}\" type=\"video/ogg\">
                    您的浏览器不支持 video 标签。
                    </video><input type='hidden' class='video_url' value='{$videoListValues[$i]}'/><img src='/images/close.png' style='float:right;' class='remove' width='30px'/></div></li>";
            }
            $strHtml .= "</ul></div><div style='clear:both'></div><br/>";
        }
        $strHtml .= "<div id=\"uploader\" class=\"wu-example\">
                    <div id=\"thelist\" class=\"uploader-list\"></div>
                    <div class=\"btns\">
                    <div id=\"".$this->buttonOptions['id']."\" style='font-size: 30px;color:black;'><input type='button' class='video_button' value='选择文件'/>
                    </div>
                    <input id=\"ctlBtn\" type='button' class=\"btn btn-default video_button\" value='开始上传'/>
                    </div>
                    </div>";
        $this->value = $this->hasModel() ? Html::getAttributeValue($this->model, $this->attribute) : $this->value;//如果当前部件从属于一个model，那么当前输入框的值就根据model和属性获取，否则就使用当前值
        //$imgurl = !empty($this->value) ? $this->value : $this->asset->baseUrl . "/upload_pic.png";//如果当前图片的url值存在就使用已经上传的图片的值；否则显示默认的图片
        if($this->hasModel()) {
            $strHtml .= Html::activeTextInput($this->model, $this->attribute, $this->options);
        }else{
            $strHtml .= Html::hiddenInput($this->name, $this->value, $this->options);
        }
        //下面的jsp要改到配置当中
       // $strHtml .= '<iframe id="alienFrame" frameborder="no" border="0" style="border: 2px solid #9F9F9F;" src="http://localhost:8080/testweb/jsp/index.jsp"></iframe>';
        echo $strHtml;
        $this->registerClientScript();
    }

    public function registerClientScript()
    {
        $jss = "";
        $jss .= <<<JS
        var uploader = WebUploader.create({
            swf: '{$this->asset->baseUrl}/ueditor/third-party/webuploader/Uploader.swf',
            chunked: true,//分片上传
            pick: '#{$this->buttonOptions['id']}',
            server: '{$this->clientOptions['serverUrl']}',
            fileVal: 'upfile',
            resize: false,
            accept: {
                title:'Videos',
                extensions:'flv,swf,mkv,avi,rm,rmvb,mpeg,mpg,ogg,ogv,mov,wmv,mp4,webm',
                mimeTypes: 'video/*'
            },
        });
        uploader.on('uploadBeforeSend', function( block, data, headers) {//文件上传前添加参数
            $.extend(data, {
                '{$this->clientOptions['csrf-param']}': '{$this->clientOptions['csrf-token']}',
            });
        });
        $('#ctlBtn').click(function(){
            uploader.upload();
        });
        // 当有文件被添加进队列的时候
        uploader.on( 'fileQueued', function( file ) {
            $('#thelist').append( '<div id="' + file.id + '" class="item">' +
                '<h4 class="info">' + file.name + '</h4>' +
                '<p class="state">等待上传...</p>' +
            '</div>' );
        });
        
        // 文件上传过程中创建进度条实时显示。
        uploader.on( 'uploadProgress', function( file, percentage ) {
                var li = $( '#'+file.id ),
                percent = li.find('.progress .progress-bar');
        
            // 避免重复创建
            if ( !percent.length ) {
                percent = $('<div class="progress progress-striped active">' +
                  '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                  '</div>' +
                '</div>').appendTo( li ).find('.progress-bar');
            }
        
            li.find('p.state').text('上传中');
        
            percent.css( 'width', percentage * 100 + '%' );
        });
        
        uploader.on( 'uploadSuccess', function( file , response) {
            if(response.state == 'SUCCESS'){
                $( '#'+file.id ).find('p.state').text('已上传');
                var orgin_val = $('#{$this->options['id']}').val();
                if(orgin_val == null || orgin_val == undefined || orgin_val == ''){
                    orgin_val = response.url;
                }else{
                    orgin_val += "#|#"+response.url;
                }
                var lii = '<li style="float:left;margin-left:5px;"><div style="position:relative;"><video width="320" height="240" controls=""><source src="'+response.url+'" type="video/mp4">'
                        +'<source src="'+response.url+'" type="video/ogg">您的浏览器不支持 video 标签。'+
                        '</video><input type="hidden" class="video_url" value="'+response.url+'"><img src="/images/close.png" style="float:right;" class="remove" width="30px"></div></li>';
                $('.videolist').append(lii);
                $('#{$this->options['id']}').val(orgin_val);
            }else{
                alert(response.state);
                $( '#'+file.id ).remove();
            }
            
        });
        
        uploader.on( 'uploadError', function( file ) {
            $( '#'+file.id ).find('p.state').text('上传出错');
        });
        
        uploader.on( 'uploadComplete', function( file ) {
            $( '#'+file.id ).find('.progress').fadeOut();
        });
        
        /*移除视频*/
        $('.remove').click(function(){
            var remove_videourl = $(this).prev('.video_url').val();
            var origin_val = $('#{$this->options['id']}').val();
            var videourl_arr = origin_val.split('#|#');
            videourl_arr.splice($.inArray(remove_videourl,videourl_arr),1);
            var val_video = videourl_arr.join('#|#');
            $(this).parents('li').remove();
            $('#{$this->options['id']}').val(val_video);
        });
JS;
        $this->view->registerJs($jss);
    }

}